package com.iss.examsys.view;

import com.iss.examsys.ejb.ExamPaperBean;
import com.iss.examsys.ejb.ExamSessionBean;
import com.iss.examsys.ejb.ExamTimerSessionBean;
import com.iss.examsys.entity.ExamPaper;
import com.iss.examsys.entity.ExamSession;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

@ViewScoped
@Named
public class ExamSessionView implements Serializable{

    private static final long serialVersionUID = 1L;
    
    private ExamSession newExamSession = new ExamSession();
    private ExamSession selectedExamSession;
    private ExamPaper examPaper;
    private Long examPaperId;
    private List<ExamSession> examSessions;  

    @EJB ExamSessionBean examSessionBean;  
    @EJB ExamPaperBean examPaperBean;
    @EJB ExamTimerSessionBean examTimerSessionBean;
    
    public ExamSessionView() {          
    }
    
    public ExamPaper getExamPaper() {
        if(examPaperId > 0) {
            setExamPaper(examPaperBean.findById(examPaperId));
        }
        return examPaper;
    }

    public void setExamPaper(ExamPaper examPaper) {
        this.examPaper = examPaper;
    }

    public Long getExamPaperId() {
        return examPaperId;
    }

    public void setExamPaperId(Long examPaperId) {
        this.examPaperId = examPaperId;
    }

    public ExamSession getSelectedExamSession() {
        return selectedExamSession;
    }

    public ExamSession getNewExamSession() {
        return newExamSession;
    }

    public void setNewExamSession(ExamSession newExamSession) {
        this.newExamSession = newExamSession;
    }

    public void setSelectedExamSession(ExamSession selectedExamSession) {
        this.selectedExamSession = selectedExamSession;
    }

    public List<ExamSession> getExamSessions() {
        setExamSessions(examSessionBean.findAll());
        return examSessions;
    }

    public void setExamSessions(List<ExamSession> examSessions) {
        this.examSessions = examSessions;
    }

    public void createBlankExamSession() {
        System.out.println(">>> at createBlankExamSession()");
        newExamSession = new ExamSession();
    }
    
    public void createExamSession() {
        System.out.println(">>> at createExamSession()");
        newExamSession.setExamPaperId(getExamPaper());
        examSessionBean.create(newExamSession);
        
        createTimer(newExamSession);
                
        examPaperId = null;
    }
    
    public void createTimer(ExamSession examSession){
        try{
            Calendar cal = Calendar.getInstance();
            cal.setTime(examSession.getDateTime());
            
            cal.add(Calendar.MINUTE, examSession.getDuration());

            examTimerSessionBean.createTimer(cal.getTime(),examSession.getId());    
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void cancelTimer(ExamSession examSession){
        try{
            examTimerSessionBean.cancelTimer(examSession.getId()+"");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void editExamSession() {
        System.out.println(">>> at editExamSession()");
        if(selectedExamSession != null) {
            Long paperId = selectedExamSession.getExamPaperId().getId();
            selectedExamSession.setExamPaperId(examPaperBean.findById(paperId));
            examSessionBean.edit(selectedExamSession);
            
            cancelTimer(selectedExamSession);
            createTimer(selectedExamSession);
        }
    }
    
    public void deleteExamSession() {    
        cancelTimer(selectedExamSession);
    }
    
    public SelectItem[] getExamPapersAvailableSelectOne() {
        return getSelectExamPaperItems(examPaperBean.findAll(), true);
    }
    
    public void validateDateTime(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        
        System.out.println(">>> at validateDateTime");
        UIInput inputId = (UIInput)component.findComponent("datetime");
                
        if(inputId != null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            try
            {
                Date date = simpleDateFormat.parse(inputId.getLocalValue().toString());
                System.out.println("datetime : "+ simpleDateFormat.format(date));
                
                if(date.before(new Date())) {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Date and time cannot be in the past.", null));
                }
            }
            catch (ParseException ex)
            {
                System.out.println("ParseException: "+ ex);
            }
        }
    }
        
    public static SelectItem[] getSelectExamPaperItems(List<ExamPaper> entities, boolean selectOne) {
        int size = selectOne ? entities.size() + 1 : entities.size();
        SelectItem[] items = new SelectItem[size];
        int i = 0;
        if (selectOne) {
            items[0] = new SelectItem("", "---");
            i++;
        }
        for (ExamPaper x : entities) {
            items[i++] = new SelectItem(x.getId(), x.getName());
        }
        return items;
    }
    
}
